package com.hugang.juc.threadpool;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * 任务的分而治之框架
 * 参考：https://baijiahao.baidu.com/s?id=1649619201425234676&wfr=spider&for=pc
 *
 * @author hg
 * @date 2020/8/21 16:45
 */
public class ForkJoinDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        System.out.println("默认 ForkJoinPool 大小 ---> " +forkJoinPool.getPoolSize());
        MyTask myTask = new MyTask(0, 1000000);
        ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(myTask);
        Integer sum = forkJoinTask.get();
        System.out.println(sum);
        forkJoinPool.shutdown();
    }


}

class MyTask extends RecursiveTask<Integer>{

    //最小分治数量
    public static final Integer FLAG = 10;
    private int start;
    private int end;
    private int result;

    public MyTask(Integer start, Integer end){
        this.start = start;
        this.end = end;
    }


    @Override
    protected Integer compute() {
        //小于最小分治数量，则不用分开算
        if ((end - start) <= FLAG){
            for (int i = start; i <= end; i++) {
                result += i;
            }
        } else {
            int middle = (end + start) / 2;
            MyTask myTask1 = new MyTask(start, middle);
            MyTask myTask2 = new MyTask(middle + 1, end);
            myTask1.fork();
            myTask2.fork();
            result = myTask1.join() + myTask2.join();
        }

        return result;
    }
}
